package com.flca.frw.validator
{
	import mx.validators.Validator;
	import mx.validators.ValidationResult;

	public class SofinumberValidator extends Validator
	{
		
		private const AANTAL_CIJFERS_SOFINR:int = 9;

		private var results:Array;

		public function SofinumberValidator() 
		{
			super();
		}
		
	    override protected function doValidation(value : Object):Array {
		    // Clear results Array.
		    results = [];
		
		    // Call base class doValidation().
		    results = super.doValidation(value);        
		    if (results.length > 0) {
		        return results;
		    }
		    
		    // Voorlopig fout als niet met 1 begint
		    if (!validateNr(value as String)) {
		        results.push(
		        	new ValidationResult(true, null, "Sofinummer/BSN", "Sofinummer/BSN is niet geldig."));
		        return results;
		    }
		    
		    return results;
		}

		private function validateNr(value:String) : Boolean {
			var sofiNummer:String = value;		
			var c1:String;
			if (sofiNummer.length == AANTAL_CIJFERS_SOFINR) {
				var calculation:Number = 0;
				var counter:int = AANTAL_CIJFERS_SOFINR;
				while (counter > 1) {
					for (var j:int = 0; j < sofiNummer.length - 1; j++) {
						c1 = sofiNummer.charAt(j);
						calculation += (counter * int(c1));
						counter--;
					}
				}

				var c2:String = sofiNummer.charAt(sofiNummer.length - 1);
				calculation = (calculation - int(c2));
				calculation /= 11;
				if (calculation % 1 == 0) {
					return true;
				} else {
				 return false;
				}
			} else {
				return false;
			}
		}
	}
}